<?php
/**
 * SecuredPresenter.php
 * @author Winbeek <winbeek@gmail.com>
 * @since 21 July 2012
 * @version $Id: SecuredPresenter.php 28 2012-08-03 10:52:04Z winbeek $
 */

use Nette\Security\User;

abstract class SecuredPresenter extends BasePresenter
{
	/** @var Nette\Database\Table\Selection $accounts */
	protected $accounts;

	/** @var Nette\Http\SessionSection $history */
	protected $history;

	// region Defaultní metody presenteru

	public function startup()
	{
		parent::startup();

		if (!$this->user->isLoggedIn()) {
			if ($this->user->logoutReason === IUserStorage::INACTIVITY)
				$this->flashMessage('Byly jste odhlášeni z důvodu neaktivity!', 'notice');
			$this->redirect('Homepage:');
		}

		$this->accounts = $this->context->createView('users');

		$this->history = $this->context->session->getSection('history');
	}

	public function beforeRender()
	{
		parent::beforeRender();

		$this->template->accounts = $this->accounts;

		if ($this->isAjax())
			$this->invalidateControl('flashMessage');
	}

	public function afterRender()
	{
		Nette\Diagnostics\Debugger::barDump($this->history, 'Historie');

		parent::afterRender();
	}

	// endregion

	// region Speciální akce

	public function actionLogout()
	{
		$this->user->logout();
		$this->redirect('Homepage:');
	}

	public function handleAdminActivate()
	{
		if ($this->user->isInRole('admin') && !$this->user->identity->adminActivated)
			$this->user->identity->adminActivated = true;

		if ($this->isAjax())
			$this->invalidateControl();
		else
			$this->redirect('this');
	}

	public function handleAdminDeactivate()
	{
		if ($this->user->isInRole('admin') && $this->user->identity->adminActivated)
			$this->user->identity->adminActivated = false;

		if ($this->isAjax())
			$this->invalidateControl();
		else
			$this->redirect('this');
	}

	// endregion

	// region Globální metody

	/**
	 * @param integer|null $id
	 * @return boolean
	 */
	protected function userExists($id = null)
	{
		return $id?isset($this->accounts[$id]):false;
	}

	// endregion
}